import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
    data: T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
    intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
        return next.handle().pipe(map(data => {
            if (!data) return ({ statusCode: 200, data: null, message: '没有数据' })
            let statusCode = data.statusCode || 200;
            let message = statusCode == 200 ? '操作成功' : '操作失败';
            message = data.message || message;
            if (statusCode == 200) return ({ statusCode, data, message })
            else return ({ statusCode, data: null, message })
        }));
    }
}